Popular Searches
Popular Course Categories
Popular Courses

AnimatedContainer in Flutter

AnimatedContainer in Flutter

Flutter Animations & UI Effects

AnimatedContainer in Flutter

AnimatedContainer is an implicitly animated version of Flutter's Container widget. It automatically animates changes to supported properties such as width, height, color, padding, margin, alignment, decoration, constraints, and transform over a specified duration. This makes it useful for creating smooth UI effects without manually managing an AnimationController.

AnimatedContainer is especially useful for interactive cards, expandable sections, buttons, hover effects, selected states, loading interfaces, and other UI components where a property needs to transition smoothly from one value to another.


1. What is AnimatedContainer?

AnimatedContainer is a Flutter widget that smoothly transitions between old and new property values whenever those properties change. It belongs to Flutter's implicit animation system.

Unlike an explicit animation, you do not normally need to create an AnimationController, TickerProvider, Tween, or animation listener for a basic AnimatedContainer animation.

AnimatedContainer(
  duration: const Duration(milliseconds: 500),
  width: 200,
  height: 100,
  color: Colors.blue,
  child: const Center(
    child: Text('Animated Container'),
  ),
)

When a property such as width, height, or color changes, Flutter automatically animates from the previous value to the new value.


2. Container vs AnimatedContainer

Container AnimatedContainer
Changes properties immediately. Animates supported property changes smoothly.
Does not require a duration. Requires a duration.
Useful for normal layouts. Useful for animated UI changes.
No implicit animation. Provides implicit animation.
Usually simpler for static UI. Useful for interactive and dynamic UI.

3. Basic Syntax

AnimatedContainer(
  duration: const Duration(milliseconds: 300),
  curve: Curves.easeInOut,
  width: 200,
  height: 100,
  color: Colors.blue,
  padding: const EdgeInsets.all(16),
  margin: const EdgeInsets.all(10),
  alignment: Alignment.center,
  child: const Text('Hello Flutter'),
)

Important Properties

  • duration - Defines how long the animation takes.
  • curve - Controls the timing and movement style of the animation.
  • width - Controls the container width.
  • height - Controls the container height.
  • color - Controls the background color.
  • padding - Controls internal spacing.
  • margin - Controls external spacing.
  • alignment - Controls the position of the child.
  • decoration - Allows animated decoration changes.
  • constraints - Allows animated constraint changes.
  • transform - Allows transformation changes.
  • onEnd - Runs a callback when the animation completes.
  • child - Defines the widget displayed inside the container.

4. How AnimatedContainer Works

AnimatedContainer uses an implicit animation mechanism. You simply rebuild the widget with different property values, and Flutter interpolates between the old and new values.

The basic flow is:

  1. The initial AnimatedContainer is displayed.
  2. A state value changes.
  3. The widget rebuilds with new AnimatedContainer properties.
  4. Flutter detects the property changes.
  5. Flutter automatically calculates the intermediate values.
  6. The container transitions smoothly to the new state.
Old Value
   ↓
Property Changes
   ↓
AnimatedContainer
   ↓
Intermediate Values
   ↓
New Value

5. Simple AnimatedContainer Example

The following example changes the container's width and color when the button is pressed.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: AnimatedContainerExample(),
    );
  }
}

class AnimatedContainerExample extends StatefulWidget {
  const AnimatedContainerExample({super.key});

  @override
  State createState() =>
      _AnimatedContainerExampleState();
}

class _AnimatedContainerExampleState
    extends State {
  bool isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('AnimatedContainer'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            AnimatedContainer(
              duration: const Duration(milliseconds: 500),
              curve: Curves.easeInOut,
              width: isExpanded ? 300 : 150,
              height: isExpanded ? 200 : 100,
              color: isExpanded ? Colors.green : Colors.blue,
              alignment: Alignment.center,
              child: const Text(
                'Hello Flutter',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                ),
              ),
            ),
            const SizedBox(height: 30),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  isExpanded = !isExpanded;
                });
              },
              child: const Text('Animate'),
            ),
          ],
        ),
      ),
    );
  }
}

What Happens?

  • Initially the container is 150 x 100.
  • When the button is pressed, its size changes to 300 x 200.
  • The color changes from blue to green.
  • AnimatedContainer smoothly transitions between the two states.

6. Why is setState() Used?

AnimatedContainer itself handles the animation, but the application still needs some mechanism to change its target values.

In a simple StatefulWidget, setState() changes the state and causes the widget tree to rebuild.

setState(() {
  isExpanded = !isExpanded;
});

After the rebuild, AnimatedContainer receives new property values and automatically animates toward them.


7. Animating Width

You can animate the width of a container by changing the width property.

AnimatedContainer(
  duration: const Duration(milliseconds: 500),
  width: isExpanded ? 300 : 100,
  height: 100,
  color: Colors.blue,
)

This can be used for expandable cards, navigation panels, search bars, and responsive controls.


8. Animating Height

The height property can also be animated.

AnimatedContainer(
  duration: const Duration(milliseconds: 400),
  width: 250,
  height: isExpanded ? 250 : 100,
  color: Colors.orange,
)

This is useful for expandable sections and card layouts.


9. Animating Width and Height Together

AnimatedContainer(
  duration: const Duration(milliseconds: 600),
  width: expanded ? 320 : 150,
  height: expanded ? 250 : 100,
  color: Colors.blue,
  child: const Center(
    child: Text(
      'Animated Box',
      style: TextStyle(color: Colors.white),
    ),
  ),
)

Multiple supported properties can animate simultaneously.


10. Animating Color

AnimatedContainer can smoothly transition between colors.

AnimatedContainer(
  duration: const Duration(milliseconds: 500),
  width: 200,
  height: 100,
  color: isActive ? Colors.green : Colors.red,
  child: const Center(
    child: Text(
      'Status',
      style: TextStyle(color: Colors.white),
    ),
  ),
)

This is useful for active/inactive states, status indicators, selected cards, and interactive buttons.


11. Animating Border Radius

Border radius can be animated through BoxDecoration.

AnimatedContainer(
  duration: const Duration(milliseconds: 500),
  width: 200,
  height: 120,
  decoration: BoxDecoration(
    color: Colors.blue,
    borderRadius: BorderRadius.circular(
      isRounded ? 50 : 10,
    ),
  ),
)

When isRounded changes, the corners smoothly transition between the two radius values.


12. Animating Decoration

The decoration property can be used to animate several visual properties together.

AnimatedContainer(
  duration: const Duration(milliseconds: 500),
  width: 220,
  height: 120,
  decoration: BoxDecoration(
    color: isSelected ? Colors.blue : Colors.white,
    borderRadius: BorderRadius.circular(
      isSelected ? 30 : 8,
    ),
    border: Border.all(
      color: isSelected ? Colors.blue : Colors.grey,
      width: 2,
    ),
    boxShadow: isSelected
        ? [
            const BoxShadow(
              blurRadius: 15,
              spreadRadius: 2,
              color: Colors.black26,
            ),
          ]
        : [],
  ),
)

This allows you to create polished selected-card and interactive UI effects.


13. Animating Padding

AnimatedContainer can smoothly change its padding.

AnimatedContainer(
  duration: const Duration(milliseconds: 400),
  padding: EdgeInsets.all(
    isExpanded ? 30 : 10,
  ),
  color: Colors.blue,
  child: const Text(
    'Animated Padding',
    style: TextStyle(color: Colors.white),
  ),
)

14. Animating Margin

AnimatedContainer(
  duration: const Duration(milliseconds: 400),
  margin: EdgeInsets.all(
    isExpanded ? 30 : 10,
  ),
  color: Colors.orange,
  child: const Text('Animated Margin'),
)

This can be useful when creating cards that move away from surrounding elements.


15. Animating Alignment

The alignment property controls where the child is positioned inside the container.

AnimatedContainer(
  duration: const Duration(milliseconds: 500),
  width: 300,
  height: 150,
  color: Colors.blue,
  alignment: isRight
      ? Alignment.centerRight
      : Alignment.centerLeft,
  child: const Padding(
    padding: EdgeInsets.all(12),
    child: Text(
      'Moving Content',
      style: TextStyle(color: Colors.white),
    ),
  ),
)

When the alignment changes, the child smoothly moves to the new position.


16. Using Curves

The curve property controls how the animation progresses over time. Flutter provides many predefined curves.

AnimatedContainer(
  duration: const Duration(milliseconds: 700),
  curve: Curves.easeInOut,
  width: isExpanded ? 300 : 150,
  height: 150,
  color: Colors.blue,
)

Common Curves

  • Curves.linear - Constant animation speed.
  • Curves.easeIn - Starts slowly and speeds up.
  • Curves.easeOut - Starts quickly and slows down.
  • Curves.easeInOut - Starts and ends smoothly.
  • Curves.fastOutSlowIn - Fast beginning followed by a slower ending.
  • Curves.bounceOut - Produces a bouncing effect.
  • Curves.elasticOut - Produces an elastic movement.

17. Understanding Duration

The duration property determines how long the transition takes.

duration: const Duration(milliseconds: 300)

Examples:

Duration Typical Effect
100 ms Very fast
300 ms Quick and responsive
500 ms Moderate and visible
800 ms Slow and noticeable
1000 ms One-second transition

The appropriate duration depends on the interaction and visual effect. Avoid unnecessarily long animations for frequent user interactions.


18. Using onEnd

The onEnd callback is called when the implicit animation completes.

AnimatedContainer(
  duration: const Duration(milliseconds: 500),
  width: isExpanded ? 300 : 150,
  height: 150,
  color: Colors.blue,
  onEnd: () {
    debugPrint('Animation completed');
  },
)

This can be useful when another action needs to occur after the animation finishes.


19. Animating Transform

AnimatedContainer can animate its transform property.

AnimatedContainer(
  duration: const Duration(milliseconds: 500),
  width: 150,
  height: 150,
  color: Colors.blue,
  transform: Matrix4.rotationZ(
    isRotated ? 0.2 : 0,
  ),
)

Transforms can be used to create rotation, scaling, translation, and other visual effects.


20. AnimatedContainer with a Card

A common real-world use case is an interactive card.

AnimatedContainer(
  duration: const Duration(milliseconds: 400),
  curve: Curves.easeInOut,
  padding: EdgeInsets.all(
    selected ? 24 : 16,
  ),
  decoration: BoxDecoration(
    color: selected
        ? Colors.blue.shade100
        : Colors.white,
    borderRadius: BorderRadius.circular(
      selected ? 24 : 12,
    ),
    border: Border.all(
      color: selected
          ? Colors.blue
          : Colors.grey.shade300,
      width: selected ? 2 : 1,
    ),
    boxShadow: selected
        ? [
            const BoxShadow(
              blurRadius: 15,
              spreadRadius: 2,
              color: Colors.black12,
            ),
          ]
        : [],
  ),
  child: const Text('Product Card'),
)

21. Practical Example: Expandable Card

import 'package:flutter/material.dart';

class ExpandableCard extends StatefulWidget {
  const ExpandableCard({super.key});

  @override
  State createState() => _ExpandableCardState();
}

class _ExpandableCardState extends State {
  bool expanded = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Expandable Card'),
      ),
      body: Center(
        child: GestureDetector(
          onTap: () {
            setState(() {
              expanded = !expanded;
            });
          },
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 500),
            curve: Curves.easeInOut,
            width: 300,
            height: expanded ? 300 : 150,
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: expanded
                  ? Colors.blue
                  : Colors.grey.shade300,
              borderRadius: BorderRadius.circular(
                expanded ? 30 : 12,
              ),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  expanded
                      ? 'Expanded Card'
                      : 'Tap to Expand',
                  style: TextStyle(
                    fontSize: 20,
                    color: expanded
                        ? Colors.white
                        : Colors.black,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                if (expanded) ...[
                  const SizedBox(height: 20),
                  const Text(
                    'Additional information is displayed here.',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.white,
                    ),
                  ),
                ],
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Important Observation

The AnimatedContainer animates its own properties, such as size, padding, decoration, and color. The child itself is not automatically animated merely because it is inside AnimatedContainer. If the child needs its own transition, use a suitable animation widget such as AnimatedSwitcher, AnimatedOpacity, or another animation technique.


22. AnimatedContainer for Button Effects

AnimatedContainer can be used to create custom interactive buttons.

GestureDetector(
  onTap: () {
    setState(() {
      isPressed = !isPressed;
    });
  },
  child: AnimatedContainer(
    duration: const Duration(milliseconds: 200),
    width: isPressed ? 180 : 200,
    height: isPressed ? 50 : 60,
    decoration: BoxDecoration(
      color: Colors.blue,
      borderRadius: BorderRadius.circular(15),
    ),
    child: const Center(
      child: Text(
        'Press Me',
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
    ),
  ),
)

23. AnimatedContainer for Selection States

Selection effects are another common use case.

AnimatedContainer(
  duration: const Duration(milliseconds: 300),
  width: 200,
  padding: const EdgeInsets.all(16),
  decoration: BoxDecoration(
    color: selected ? Colors.blue : Colors.white,
    borderRadius: BorderRadius.circular(16),
    border: Border.all(
      color: selected ? Colors.blue : Colors.grey,
      width: selected ? 3 : 1,
    ),
  ),
  child: Text(
    'Option A',
    style: TextStyle(
      color: selected ? Colors.white : Colors.black,
    ),
  ),
)

24. AnimatedContainer and Forms

AnimatedContainer can improve form interfaces by highlighting focused or active sections.

AnimatedContainer(
  duration: const Duration(milliseconds: 300),
  padding: const EdgeInsets.all(16),
  decoration: BoxDecoration(
    color: isFocused
        ? Colors.blue.withOpacity(0.08)
        : Colors.grey.shade100,
    borderRadius: BorderRadius.circular(
      isFocused ? 16 : 8,
    ),
    border: Border.all(
      color: isFocused
          ? Colors.blue
          : Colors.grey.shade300,
    ),
  ),
  child: const TextField(
    decoration: InputDecoration(
      border: InputBorder.none,
      hintText: 'Enter your name',
    ),
  ),
)

25. AnimatedContainer and Responsive UI

AnimatedContainer can be useful when UI dimensions change because of user interaction. However, normal responsive layouts should still rely on appropriate layout widgets such as Row, Column, Expanded, Flexible, Wrap, and responsive constraints rather than using animation as a replacement for layout.


26. What AnimatedContainer Does Not Animate

AnimatedContainer animates supported property changes, but not every aspect of its child.

  • The child widget itself is not automatically animated.
  • Changing the child does not automatically create a child transition.
  • Complex animation sequences may require explicit animation APIs.
  • Properties that are null are not animated.

For child transitions, consider widgets such as AnimatedSwitcher. For highly customized animations, consider AnimationController, Tween, and AnimatedBuilder.


27. AnimatedContainer vs AnimationController

AnimatedContainer AnimationController
Implicit animation. Explicit animation.
Simple to implement. Requires more code.
Automatically handles interpolation. Developer controls animation progress.
No manual controller required. Requires an AnimationController.
Good for common property transitions. Good for complex and highly controlled animations.
Limited control over animation lifecycle. Supports forward, reverse, repeat, stop, reset, and more.

28. When Should You Use AnimatedContainer?

  • When you need a simple property transition.
  • When a container changes size.
  • When a container changes color.
  • When border radius needs to animate.
  • When padding or margin changes.
  • When alignment changes.
  • When decoration changes.
  • When creating interactive cards.
  • When creating expandable UI components.
  • When creating simple button or selection effects.

29. When Should You Avoid AnimatedContainer?

  • When you need precise control over animation progress.
  • When the animation needs to be paused or resumed manually.
  • When several animations need to run in a carefully coordinated sequence.
  • When you need complex staggered animations.
  • When you need direct access to animation values.
  • When a custom animation controller is required.

In these situations, explicit animation APIs such as AnimationController, Tween, CurvedAnimation, and AnimatedBuilder may be more appropriate.


30. Common Mistakes

Mistake 1: Forgetting Duration

AnimatedContainer(
  width: 200,
)

AnimatedContainer requires a duration. Always specify an appropriate duration.

Mistake 2: Expecting the Child to Animate

AnimatedContainer animates its supported properties, but its child and descendants are not automatically animated.

Mistake 3: Using Excessively Long Durations

Very long animations can make normal interactions feel slow.

Mistake 4: Using AnimationController for Simple Effects

If a simple property transition can be handled by AnimatedContainer, manually creating an AnimationController may add unnecessary complexity.

Mistake 5: Rebuilding Large Widget Trees Unnecessarily

Keep the changing state as close as practical to the widget that needs it so that unrelated parts of the UI do not rebuild unnecessarily.


31. Performance Considerations

  • Keep animations simple when possible.
  • Avoid animating unnecessarily large or expensive widget trees.
  • Use appropriate durations and curves.
  • Avoid excessive simultaneous animations.
  • Use explicit animation techniques when complex animation control is genuinely required.
  • Test animations on real target devices, especially lower-powered devices.

32. Best Practices

  1. Use AnimatedContainer for simple implicit transitions.
  2. Choose a duration appropriate for the interaction.
  3. Use curves to create natural movement.
  4. Keep animation behavior predictable.
  5. Do not animate every UI change unnecessarily.
  6. Use semantic state variables such as isExpanded, isSelected, or isActive.
  7. Use onEnd only when an action genuinely needs to happen after the transition.
  8. Use explicit animations when you need advanced control.
  9. Test animations for performance and accessibility.

33. Real-World Applications

Use Case AnimatedContainer Property
Expandable card Width, height, padding
Selected card Color, border, radius, shadow
Custom button Width, height, color
Profile card Padding, radius, decoration
Dashboard widget Size, color, alignment
Menu panel Width, alignment
Status indicator Color, size, decoration
Interactive form section Padding, border, color

34. Mini Project: Interactive Animated Card

Try building a product card with the following behavior:

  • Normal card has a small border.
  • Selected card changes background color.
  • Selected card gets a larger border radius.
  • Selected card receives a shadow.
  • Card padding increases.
  • All changes happen smoothly using AnimatedContainer.
AnimatedContainer(
  duration: const Duration(milliseconds: 400),
  curve: Curves.easeInOut,
  padding: EdgeInsets.all(
    selected ? 24 : 16,
  ),
  decoration: BoxDecoration(
    color: selected
        ? Colors.blue.shade50
        : Colors.white,
    borderRadius: BorderRadius.circular(
      selected ? 24 : 12,
    ),
    border: Border.all(
      color: selected
          ? Colors.blue
          : Colors.grey.shade300,
      width: selected ? 2 : 1,
    ),
    boxShadow: selected
        ? const [
            BoxShadow(
              blurRadius: 12,
              spreadRadius: 1,
              color: Colors.black12,
            ),
          ]
        : [],
  ),
  child: const Text(
    'Flutter Product',
    style: TextStyle(
      fontSize: 18,
      fontWeight: FontWeight.bold,
    ),
  ),
)

35. AnimatedContainer Development Process

  1. Identify the property that should change.
  2. Create a state variable representing the UI state.
  3. Update the state using setState() or another state-management approach.
  4. Use the state variable to provide the AnimatedContainer's target property values.
  5. Set an appropriate duration.
  6. Choose a suitable curve.
  7. Test the animation on different screen sizes and devices.
  8. Use explicit animation APIs if the animation requirements become more complex.

36. Quick Revision

  • AnimatedContainer is an implicitly animated version of Container.
  • It automatically animates supported property changes.
  • A duration is required.
  • curve controls the animation timing.
  • onEnd runs after the animation completes.
  • Commonly animated properties include width, height, color, padding, margin, alignment, decoration, constraints, and transform.
  • The child itself is not automatically animated.
  • AnimatedContainer is ideal for simple UI transitions.
  • Complex animation requirements may be better handled with explicit animations.

37. Interview Questions

Q1. What is AnimatedContainer in Flutter?

AnimatedContainer is an implicitly animated version of Container that smoothly transitions supported property values when they change.

Q2. Is AnimationController required for AnimatedContainer?

No. AnimatedContainer manages its implicit animation internally.

Q3. Why is duration required?

The duration specifies how long the transition should take.

Q4. What is the purpose of the curve property?

The curve controls the timing behavior of the animation, such as linear, ease-in, ease-out, or ease-in-out movement.

Q5. Can AnimatedContainer animate color?

Yes. It can smoothly transition between supported color values.

Q6. Can AnimatedContainer animate border radius?

Yes. Border radius can be changed through a BoxDecoration and AnimatedContainer can interpolate the supported decoration changes.

Q7. Does AnimatedContainer animate its child?

No. The child and its descendants are not automatically animated by AnimatedContainer.

Q8. What is onEnd used for?

onEnd is called when the implicit animation finishes.

Q9. When should AnimationController be used instead?

Use an AnimationController when you need detailed control over animation progress, lifecycle, direction, repetition, sequencing, or other advanced animation behavior.

Q10. What is the difference between implicit and explicit animation?

Implicit animation widgets such as AnimatedContainer automatically manage the transition when target values change. Explicit animations give the developer direct control using objects such as AnimationController and Animation.


38. Learning Outcome

After studying AnimatedContainer, you should be able to:

  • Explain what AnimatedContainer is.
  • Understand implicit animations in Flutter.
  • Animate container dimensions.
  • Animate colors and decorations.
  • Animate padding and margin.
  • Animate alignment and transforms.
  • Use animation curves.
  • Use animation duration effectively.
  • Use onEnd callbacks.
  • Create expandable and interactive cards.
  • Build animated selection states.
  • Choose between AnimatedContainer and explicit animation APIs.

39. Useful Flutter Resources

For official Flutter API information, refer to the Flutter documentation and API reference for AnimatedContainer. AnimatedContainer is part of Flutter's implicit animation system.


40. JustAcademy Flutter Resources

Learn more about Flutter development through the following resources:


41. Summary

AnimatedContainer is one of the easiest ways to add smooth animations to Flutter interfaces. It provides implicit animation for supported Container properties, allowing developers to animate changes in size, color, padding, margin, alignment, decoration, constraints, and transforms without manually creating an AnimationController.

The basic idea is simple: change the target property values, rebuild the widget, and AnimatedContainer smoothly transitions from the previous values to the new values. For simple UI interactions, this approach keeps animation code short and readable. For advanced animation requirements such as precise control, complex sequences, manual progress, or coordinated animations, Flutter's explicit animation APIs can be used instead.

whatsapp